package cn.lili.controller.goods;

import cn.lili.common.context.ThreadContextHolder;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.service.GoodsImportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author chc
 * @since 2022/6/2114:46
 */
@Api(tags = "商品导入")
@RestController
@RequestMapping("/goods/import")
@RequiredArgsConstructor
public class GoodsImportController {

    private final GoodsImportService goodsImportService;


    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation(value = "上传文件，商品批量添加")
    public ResultMessage<Object> importExcel(@RequestPart("files") MultipartFile files) {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        try {
            goodsImportService.importExcel(files, currentUser.getScene().name());
            return ResultUtil.success();
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(ResultCode.FILE_IMPORT_ERROR);
        }

    }


    @ApiOperation(value = "下载导入模板", produces = "application/octet-stream")
    @GetMapping(value = "/downLoad")
    public void download() {
        AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        HttpServletResponse response = ThreadContextHolder.getHttpResponse();

        goodsImportService.download(response, currentUser.getExtendId(), currentUser.getScene().name());
    }
}
